import { getLatestVersion, compareVersions } from "@/api/version";
import { getAppVersion } from "@/config/app";

// 更新工具类
class UpdateUtils {
  constructor() {
    this.currentVersion = getAppVersion();
    this.versionInfo = {};
    this.downSize = 0;
    this.fileSize = 0;
    this.downloadProgress = 0;
    this.isDownloading = false;
    this.downloadComplete = false;
    this.downloadFilePath = "";
    this.isUserInitiated = false; // 标记是否是用户主动检查更新
    this.updateCallbacks = {
      onCheckStart: null,
      onCheckComplete: null,
      onDownloadStart: null,
      onDownloadProgress: null,
      onDownloadComplete: null,
      onInstallStart: null,
      onInstallComplete: null,
      onInstallFail: null,
      onUpdateAvailable: null,
    };
  }

  // 设置回调函数
  setCallbacks(callbacks) {
    this.updateCallbacks = { ...this.updateCallbacks, ...callbacks };
  }

  // 检查更新
  async checkUpdate(showUpdateModal = true) {
    try {
      if (this.updateCallbacks.onCheckStart) {
        this.updateCallbacks.onCheckStart();
      }

      const res = await getLatestVersion();

      // 检查完成后重置标志
      const userInitiated = this.isUserInitiated;
      this.isUserInitiated = false;

      if (res && compareVersions(res.version, this.currentVersion) > 0) {
        this.versionInfo = res;

        if (this.updateCallbacks.onUpdateAvailable) {
          this.updateCallbacks.onUpdateAvailable(res);
        }

        if (showUpdateModal) {
          if (this.updateCallbacks.onCheckComplete) {
            this.updateCallbacks.onCheckComplete(true, res);
          }
          return { hasUpdate: true, versionInfo: res };
        } else {
          if (this.updateCallbacks.onCheckComplete) {
            this.updateCallbacks.onCheckComplete(true, res);
          }
          return { hasUpdate: true, versionInfo: res };
        }
      } else {
        if (this.updateCallbacks.onCheckComplete) {
          // 传递是否由用户主动检查的标志
          this.updateCallbacks.onCheckComplete(
            false,
            null,
            null,
            userInitiated
          );
        }
        return { hasUpdate: false };
      }
    } catch (error) {
      console.error("检查更新失败：", error);
      // 重置标志
      const userInitiated = this.isUserInitiated;
      this.isUserInitiated = false;

      if (this.updateCallbacks.onCheckComplete) {
        this.updateCallbacks.onCheckComplete(false, null, error);
      }
      return { hasUpdate: false, error };
    }
  }

  // 开始下载新版本
  startDownload() {
    //#ifdef APP-PLUS
    if (!this.versionInfo.downloadUrl) return false;

    // 如果已经在下载，不重复开始
    if (this.isDownloading) return true;

    this.isDownloading = true;
    this.downloadProgress = 0;
    this.downSize = 0;
    this.downloadComplete = false;

    if (this.updateCallbacks.onDownloadStart) {
      this.updateCallbacks.onDownloadStart();
    }

    let dtask = plus.downloader.createDownload(
      this.versionInfo.downloadUrl,
      {},
      (d, status) => {
        if (status == 200) {
          this.fileSize = d.totalSize;
          this.downloadComplete = true;
          this.downloadFilePath = d.filename;
          this.isDownloading = false;
          console.log("下载完成：" + d.filename);

          if (this.updateCallbacks.onDownloadComplete) {
            this.updateCallbacks.onDownloadComplete(d.filename);
          }
        } else {
          console.error("下载失败：" + status);
          this.isDownloading = false;

          if (this.updateCallbacks.onDownloadComplete) {
            this.updateCallbacks.onDownloadComplete(
              null,
              new Error("下载失败，状态码：" + status)
            );
          }
        }
      }
    );

    // 监听下载进度
    dtask.addEventListener("statechanged", (task, status) => {
      switch (task.state) {
        case 2: // 已连接到服务器
          console.log("已连接到服务器");
          break;
        case 3: // 已接收到数据
          this.downSize = task.downloadedSize;
          this.fileSize = task.totalSize || this.fileSize;
          if (this.fileSize > 0) {
            this.downloadProgress = Math.floor(
              (this.downSize / this.fileSize) * 100
            );

            if (this.updateCallbacks.onDownloadProgress) {
              this.updateCallbacks.onDownloadProgress({
                progress: this.downloadProgress,
                downloadedSize: this.downSize,
                totalSize: this.fileSize,
              });
            }
          }
          console.log(`下载进度：${this.downloadProgress}%`);
          break;
        case 4: // 下载完成
          this.downloadComplete = true;
          break;
      }
    });

    dtask.start();
    return true;
    //#endif

    // 非APP环境
    return false;
  }

  // 安装更新
  installUpdate() {
    if (this.downloadComplete && this.downloadFilePath) {
      this.installApp(this.downloadFilePath);
      return true;
    }
    return false;
  }

  // 安装应用
  installApp(path) {
    //#ifdef APP-PLUS
    if (this.updateCallbacks.onInstallStart) {
      this.updateCallbacks.onInstallStart();
    }

    plus.runtime.install(
      path,
      {
        force: true, // 强制安装，不进行版本号校验
      },
      () => {
        console.log("安装成功，准备重启应用");

        if (this.updateCallbacks.onInstallComplete) {
          this.updateCallbacks.onInstallComplete();
        }

        // 安装成功后延迟重启应用
        setTimeout(() => {
          this.restartApp();
        }, 200);
      },
      (e) => {
        console.error("安装失败[" + e.code + "]：" + e.message);

        if (this.updateCallbacks.onInstallFail) {
          this.updateCallbacks.onInstallFail(e);
        }
      }
    );
    //#endif
  }

  // 重启应用
  restartApp() {
    //#ifdef APP-PLUS
    plus.runtime.restart();
    //#endif
  }

  // 获取当前下载状态
  getDownloadStatus() {
    if (this.downloadComplete) {
      return "completed";
    } else if (this.isDownloading) {
      return "downloading";
    } else {
      return "not_started";
    }
  }
}

// 导出单例
const updateUtils = new UpdateUtils();
export default updateUtils;
